<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/6/13
 * Time: 上午9:15
 */

namespace Common\Service;


class GuguapiService extends BaseService
{

    private $ak = '9c7a33c406374a07bd5554a2d1b21d03';
    // access key
    private $url = array(
        'getUserId' => 'http://open.memobird.cn/home/setuserbind/',
        'printPaper' => 'http://open.memobird.cn/home/printpaper/',
        'getPrintStatus' => 'http://open.memobird.cn/home/getprintstatus/'
    );

    public $font;

    function __construct()
    {
        date_default_timezone_set('PRC');
        $this->_get_font();
    }

    /*
     * 获取字体
     * songti siyuan  kaiti  mao jinglei shaonv
     */
    protected function _get_font($font=false){

        if(!$font){
            $font = "songti";
        }
        $fontfile = ROOT."/Static/mobile/font/".$font.".ttf";
        $this->font = $fontfile;
        return $fontfile;

    }


    // 构造printPaper方法中$printcontent格式，多个可以循环并用|拼接
    protected function _contentSet($type, $content)
    {
        switch ($type) {
            case 'T':
                $ret = $type . ':' . base64_encode($this->_charsetToGBK($content) . "\n");
                break;
            case 'P':
                $ret = 'P:' . base64_encode($content);
                break;
            default:
        }
        return $ret;
    }




    /**
     * 发起 server 请求
     *
     * @param
     *            $action
     * @param
     *            $params
     * @param
     *            $httpHeader
     * @return mixed
     */
    protected function _curl($action, $params)
    {
        // $action = self::SERVERAPIURL.$action.'.'.$this->format;
        // $httpHeader = $this->createHttpHeader();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $action);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 处理http证书问题
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        if (false === $ret) {
            $ret = curl_errno($ch);
        }
        curl_close($ch);
        return $ret;
    }

    protected function _charsetToGBK($mixed)
    {
        if (is_array($mixed)) {
            foreach ($mixed as $k => $v) {
                if (is_array($v)) {
                    $mixed[$k] = $this->_charsetToGBK($v);
                } else {
                    $encode = mb_detect_encoding($v, array(
                        'ASCII',
                        'UTF-8',
                        'GB2312',
                        'GBK',
                        'BIG5'
                    ));
                    if ($encode == 'UTF-8') {
                        $mixed[$k] = iconv('UTF-8', 'GBK', $v);
                    }
                }
            }
        } else {
            $encode = mb_detect_encoding($mixed, array(
                'ASCII',
                'UTF-8',
                'GB2312',
                'GBK',
                'BIG5'
            ));
            // var_dump($encode);
            if ($encode == 'UTF-8') {
                $mixed = iconv('UTF-8', 'GBK', $mixed);
            }
        }
        return $mixed;
    }


    // 生成单色点位图 bmp图片
    protected function _imagebmp($im, $out = false)
    {

        //如果超过384宽度,缩小宽度到384
        $width = imagesx($im);
        if($width>384){
            $im = $this->_resizeImage($im,384);
        }

        //进行灰度处理
        imagefilter($im, IMG_FILTER_GRAYSCALE);

        $compression = 0;
        $bit = 1;

        $bits = pow(2, $bit);

        // 调整调色板
        imagetruecolortopalette($im, true, $bits);
        $width = imagesx($im);

        $height = imagesy($im);
        $colors_num = imagecolorstotal($im);

        // 颜色索引
        $rgb_quad = '';
        for ($i = 0; $i < $colors_num; $i ++) {
            $colors = imagecolorsforindex($im, $i);
            $rgb_quad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
        }

        // 位图数据
        $bmp_data = '';

        $compression = 0;

        // 每行字节数必须为4的倍数，补齐。
        $extra = '';
        $padding = 4 - ceil($width / (8 / $bit)) % 4;
        if ($padding % 4 != 0) {
            $extra = str_repeat("\0", $padding);
        }

        for ($j = $height - 1; $j >= 0; $j --) {
            $i = 0;
            while ($i < $width) {
                $bin = 0;
                $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;

                for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
                    $index = imagecolorat($im, $i, $j);
                    $bin |= $index << $k;
                    $i ++;
                }

                $bmp_data .= chr($bin);
            }

            $bmp_data .= $extra;
        }

        $size_quad = strlen($rgb_quad);
        $size_data = strlen($bmp_data);

        // 位图文件头
        $file_header = "BM" . pack("V3", 54 + $size_quad + $size_data, 0, 54 + $size_quad);

        // 位图信息头
        $info_header = pack("V3v2V*", 0x28, $width, $height, 1, $bit, $compression, $size_data, 0, 0, $colors_num, 0);

        imagedestroy($im);

        if($out){
            //浏览器输出
            header("Content-Type: image/bmp");
            echo $file_header . $info_header;
            echo $rgb_quad;
            echo $bmp_data;
            exit;
        }
        //返回值
        return $file_header . $info_header . $rgb_quad . $bmp_data;
    }

    // 等比缩放
    protected function _resizeImage($im, $maxwidth = '', $maxheight = '')
    {
        $pic_width = imagesx($im);
        $pic_height = imagesy($im);

        if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
            if ($maxwidth && $pic_width > $maxwidth) {
                $widthratio = $maxwidth / $pic_width;
                $resizewidth_tag = true;
            }

            if ($maxheight && $pic_height > $maxheight) {
                $heightratio = $maxheight / $pic_height;
                $resizeheight_tag = true;
            }

            if ($resizewidth_tag && $resizeheight_tag) {
                if ($widthratio < $heightratio) {
                    $ratio = $widthratio;
                } else {
                    $ratio = $heightratio;
                }
            }

            if ($resizewidth_tag && ! $resizeheight_tag) {
                $ratio = $widthratio;
            }
            if ($resizeheight_tag && ! $resizewidth_tag) {
                $ratio = $heightratio;
            }

            $newwidth = $pic_width * $ratio;
            $newheight = $pic_height * $ratio;

            if (function_exists("imagecopyresampled")) {
                $newim = imagecreatetruecolor($newwidth, $newheight);
                imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
            } else {
                $newim = imagecreate($newwidth, $newheight);
                imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
            }
            return $newim;
        } else {
            return $im;
        }
    }

    /*
     * 获取文字区域的宽度高度
     */
    protected function _textBox($text,$fontsize=10,$font='',$angle=0){

        if(!$font){
            $font = $this->font;
        }
        $box =  imagettfbbox($fontsize, $angle, $font, $text);

        $width = $box[4] - $box[6];

        $height = $box[3] - $box[5];

        return array(
            "h" => $height,
            "w" => $width
        );
    }

    /**
     * @desc GD库生成图片中文自动换行
     * 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
     * */
    protected function _autowrap($string,$fontsize=10, $angle=0, $font='', $width=384,$padding) {

        if(!$font){
            $font = $this->font;
        }

        $content = "";
        $leng = mb_strlen($string,"UTF-8");
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<$leng;$i++) {
            $letter[] = mb_substr($string, $i, 1,"UTF-8");
        }

        $box = imagettfbbox($fontsize, $angle, $font, "我");
        $twidth = $box[4] - $box[6];

        $i = 1;
        $width = $width - $padding*2;
        foreach ($letter as $key=>$l){

            $teststr = $content."".$l;
            // $tt = $i*$twidth;

            $box = imagettfbbox($fontsize, $angle, $font, $teststr);
            $tt = $box[2];

            $i++;
            // 判断拼接后的字符串是否超过预设的宽度
            if (($tt > $width) && ($content !== "")) {
                $content .= "\n";
                $i = 0;
            }
            $content .= $l;

        }
        return $content;

    }




    /** 画圆角
     * @param $radius 圆角位置
     * @param $color_r 色值0-255
     * @param $color_g 色值0-255
     * @param $color_b 色值0-255
     * @return resource 返回圆角
     */
    protected function _get_lt_rounder_corner($radius, $color_r, $color_g, $color_b)
    {
        // 创建一个正方形的图像
        $img = imagecreatetruecolor($radius, $radius);
        // 图像的背景
        $bgcolor = imagecolorallocate($img, $color_r, $color_g, $color_b);
        $fgcolor = imagecolorallocate($img, 0, 0, 0);
        imagefill($img, 0, 0, $bgcolor);
        // $radius,$radius：以图像的右下角开始画弧
        // $radius*2, $radius*2：已宽度、高度画弧
        // 180, 270：指定了角度的起始和结束点
        // fgcolor：指定颜色
        imagefilledarc($img, $radius, $radius, $radius * 2, $radius * 2, 180, 270, $fgcolor, IMG_ARC_PIE);
        // 将弧角图片的颜色设置为透明
        imagecolortransparent($img, $fgcolor);
        return $img;
    }


    /**
     * @param $im  大的背景图，也是我们的画板
     * @param $lt_corner 我们画的圆角
     * @param $radius  圆角的程度
     * @param $image_h 图片的高
     * @param $image_w 图片的宽
     */
    protected function _myradus($im, $lift, $top, $lt_corner, $radius, $image_h, $image_w)
    {
        /// lt(左上角)
        imagecopymerge($im, $lt_corner, $lift, $top, 0, 0, $radius, $radius, 100);
        // lb(左下角)
        $lb_corner = imagerotate($lt_corner, 90, 0);
        imagecopymerge($im, $lb_corner, $lift, $image_h - $radius + $top, 0, 0, $radius, $radius, 100);
        // rb(右上角)
        $rb_corner = imagerotate($lt_corner, 180, 0);
        imagecopymerge($im, $rb_corner, $image_w + $lift - $radius, $image_h + $top - $radius, 0, 0, $radius, $radius, 100);
        // rt(右下角)
        $rt_corner = imagerotate($lt_corner, 270, 0);
        imagecopymerge($im, $rt_corner, $image_w - $radius + $lift, $top, 0, 0, $radius, $radius, 100);
    }

    /*
     * 图片圆角处理
     * $radius 圆角大小
     */
    protected function _rounderPic($im,$radius=15){

        //画圆角
        $lt_corner = $this->_get_lt_rounder_corner($radius, 255, 255, 255);
        //圆角的背景色
        $width = imagesx($im);
        $height = imagesy($im);
        $this->_myradus($im, 0, 0, $lt_corner, $radius, $height,$width);
        return $im;

    }

    public function openImage ($file) {
        //detect type and process accordinally
        $size=getimagesize($file);
        switch($size["mime"]){
            case "image/jpeg":
                $im = imagecreatefromjpeg($file); //jpeg file
                break;
            case "image/gif":
                $im = imagecreatefromgif($file); //gif file
                break;
            case "image/png":
                $im = imagecreatefrompng($file); //png file
                break;
            default:
                $im=false;
                break;
        }
        return $im;
    }


    /*
     * 获取打印状态
     */
    public function getPaperStatus($printcontentID)
    {
        $params = array(
            'ak' => $this->ak,
            'timestamp' => date('Y-m-d h:m:s', time()),
            'printcontentID' => $printcontentID
        );
        $paramsString = http_build_query($params);
        return $this->_curl($this->url['getPrintStatus'], $paramsString);
    }

    /*
     * 关联设备
     * 返回userid
     */
    public function getUserId($memobirdID, $useridentifying)
    {
        $params = array(
            'ak' => $this->ak,
            'timestamp' => date('Y-m-d h:m:s', time()),
            'memobirdID' => $memobirdID,
            'useridentifying' => $useridentifying
        );
        $paramsString = http_build_query($params);
        $json_str = $this->_curl($this->url['getUserId'], $paramsString);

        $json = json_decode($json_str, true);
        if ($json['showapi_res_code'] == 1) {
            $userid = $json['showapi_userid'];
            return $userid;
        }
        return false;
    }

    /*
     * 打印纸条
     *
     */
    public function printPaper($printcontent, $memobirdID, $userID)
    {
        //如果内容是数组,拼接起来
        if(is_array($printcontent)){
            $p = array_reverse($printcontent);
            $printcontent = implode('|',$p);
        }
        $params = array(
            'ak' => $this->ak,
            'timestamp' => date('Y-m-d h:m:s', time()),
            'printcontent' => $printcontent,
            'memobirdID' => $memobirdID,
            'userID' => $userID
        );
        $paramsString = http_build_query($params);
        $data = array(
            "content" => $paramsString,
            'create_time'=>date('Y-m-d H:i:s'),
        );
        $id = M("backopen")->add($data);
        $url = "/Miniproapi/ThirdGugu/printBackOpen?id=".$id;
        $this->_backOpen($url);
        return $id;
    }


    /*
     * 获取打印文字图片的数据格式
     * 正文用18号字 ,人名用80号字
     * $font = songti siyuan  kaiti  mao jinglei shaonv
     */
    public function printTextPic($text,$font='',$fontsize=15,$left,$top,$padding=10,$width=384,$height='',$angle=0,$border=0){

        //字体所放目录
        if(!$font){
            $font = $this->font;
        }else{
            $font = $this->_get_font($font);//songti siyuan  kaiti  mao jinglei shaonv
        }

        $text = $this->_autowrap($text,$fontsize, $angle, $font, $width,$padding);//自动换行

        $box = $this->_textBox($text,$fontsize,$font,$angle);

        if(!$top){
            $box2 =  imagettfbbox($fontsize, $angle, $font, "我");
            $top = $box2[3] - $box2[5]+$padding;
        }

        if(!$height){
            if(!$padding){
                $padding = 10;
            }
            $height = $box['h'] + $padding*2;
        }

        if(!$left){
            $left = ($width - $box['w'])/2;
        }

        if($top<20){
            $top = 20;
        }

        $im =imagecreate($width,$height);

        $background_color = ImageColorAllocate ($im, 255, 255, 255);

        $col = imagecolorallocate($im, 0, 0, 0);//字体颜色

        if($border){
            //画一个矩形边框
            imagerectangle($im,2,2,$width-2,$height-2,$col);
        }

        imagettftext($im,$fontsize,$angle,$left,$top,$col,$font,$text); //写 TTF 文字到图中

//           header('Content-type: image/png');
//           imagepng($im);exit;

        $printcontent = $this->printPic($im);

        return $printcontent;

    }

    /*
     * 打印图片
     */
    public function printPic($im){

        $width = imagesx($im);
        $height = imagesy($im);

        //创建一个新的图片资源，用来保存沿Y轴翻转后的图片
        $new = imagecreatetruecolor($width, $height);
        //图像水平翻转
        for($x=0 ;$x<$width; $x++){
            //逐条复制图片本身高度，1个像素宽度的图片到薪资源中
            imagecopy($new, $im, $width-$x-1, 0, $x, 0, 1, $height);
        }

        $bmp = $this->_imagebmp($new);//生成图片

        $printcontent = $this->_contentSet("P",$bmp);//拼接图片格式

        return $printcontent;

    }

    /*
     * 打印二维码
 * @param    string $text 文本内容
 * @param    int $level   纠错级别
 * @param    int $size 尺寸
 * @param    int margin 边框留白尺寸
     */
    public function printQrcode($text,$level = 1,$size = 8, $margin = 1){

        $name = md5($text);
        $outfile = ROOT."/upload/tmp/".$name;
        $im = qrcode($text, $outfile, $level, $size, $margin);
        $im = imagecreatefrompng($outfile);
        $result = @unlink ($outfile);//删除文件
        return $this->printPic($im);

    }

    /*
     * 直接打印普通文本
     * 注意 打印的方向与图片的方向相反
     */
    public function printText($text){

        $printcontent = $this->_contentSet("T",$text);//拼接图片格式
        return $printcontent;

    }


    /*
     * 打印分割线 裁剪线条
     * $bold = 1 细线
     * $bold = 2 粗线
     */
    public function printLine($bold=1){

        if($bold==1){
            $txt = "--------------------------------------------------------------------------------------------";
            $size = 5;
        }else if($bold==2){
            $txt = "--------------------------------------";
            $size = 15;
        }

        $printcontent =  $this->printTextPic($txt,"songti",$size,'','',0,384,'');
        return $printcontent;

    }

    /*
     * 异步执行
     *      * Array
     * (
     * [showapi_res_code] => 1
     * [showapi_res_error] => ok
     * [result] => 2
     * [smartGuid] => d0563729838867e8
     * [printcontentid] => 5436771
     */
    public function backOpen($id){

        $dres = M("backopen")->where(array('id'=>$id))->find();
        if(empty($dres)){
            return_json(1,"EMPTY");
        }

        if($dres['status'] >0){
            return_json(1,"DOING");
        }

        //更改为正在发送
        $data = array(
            'send_time' => date("Y-m-d H:i:s"),
            'status' => 3,//正在发送
        );
      // M("backopen")->where(array('id'=>$id))->save($data);
        $json_str = $this->_curl($this->url['printPaper'], $dres['content']);
        $res = json_decode($json_str, true);
        if (isset($res['showapi_res_code']) && ($res['showapi_res_code'] == 1)) {
            // 发送成功
            $data = array(
                'send_time' => date("Y-m-d H:i:s"),
                'status' => 1,
                'errmsg' => $res['showapi_res_error'],
                'result' => $res['result'],
                'printcontentid' => $res['printcontentid'],
                'memobirdid' => $res['smartGuid'],
            );

        } else {

            // 发送失败
            $data = array(
                'send_time' => date("Y-m-d H:i:s"),
                'status' => 2,
                'errmsg' => $res['showapi_res_error'],
            );

        }

        $res = M("backopen")->where(array('id'=>$id))->save($data);
        return_json(0,"DONE");

    }

    /*
     * 异步执行
     */
    protected function _backOpen($url){

        $domain = $_SERVER['HTTP_HOST'];
        $fp = fsockopen($domain, 80, $errno, $errstr, 10);
        if (!$fp) {
            return false;
            //echo "$errstr ($errno)<br />\n";
        } else {
            $out = "GET ".$url."  / HTTP/1.1\r\n";
            $out .= "Host: ".$domain."\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            /*忽略执行结果
             while (!feof($fp)) {
             echo fgets($fp, 128);
            }*/
            fclose($fp);
        }
    }

}